package com.iss.card.view.account.shake;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.model.CityDataManager;
import com.iss.card.model.StoreAddressInfo;
import com.iss.card.view.ContainerActivity;
import com.iss.card.view.account.shake.ShakeListener.OnShakeListener;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

public class ShakeView implements IBackKeyListener {
	private final static String TAG = ShakeView.class.getSimpleName();
	private ShakeListener mShakeListener;
	private Context mContext;

	private View mRootView;
	private View mBeforeView;
	private View mAfterView;
	private TextView mStoreName;
	private TextView mStoreAddress;
	private SoundPool mSoundPool;
	private int mSoundID;
	private StoreAddressInfo mRandomStore;

	public ShakeView(Context context, View layout) {
		this.mContext = context;
		mRootView = layout;
		mBeforeView = layout.findViewById(R.id.iv_pop_shake);
		mAfterView = layout.findViewById(R.id.rv_pop_shake_result);
		mStoreName = (TextView) layout
				.findViewById(R.id.tv_pop_shake_store_name);
		mStoreAddress = (TextView) mRootView
				.findViewById(R.id.tv_pop_shake_store_address);
		mStoreName.setOnClickListener(mGotoSeeStoreDetail);
		mStoreAddress.setOnClickListener(mGotoSeeStoreDetail);
		mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
		mSoundID = mSoundPool.load(mContext, R.raw.water, 1);
		Button cancel = (Button) layout.findViewById(R.id.return_button);
		cancel.setBackgroundResource(R.drawable.return_selector);
		cancel.setVisibility(View.VISIBLE);
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((Activity) mContext).finish();
			}
		});

		((TextView) layout.findViewById(R.id.job_name_val))
				.setText(R.string.more_shake);
		mShakeListener = new ShakeListener(context);
		init();
	}

	public void onDestroy() {
		Log.d(TAG, "onDestroy");
		mShakeListener.stop();
	}
	
	private void init() {
		mShakeListener.setOnShakeListener(new OnShakeListener() {
			public void onShake() {
				mShakeListener.stop();
				requestGetRandomCity();
				playSounds(mSoundID);
				// show animation as the first time, only refresh content for
				// additional shake.
				if (mBeforeView.isShown()) {
					ViewTranslateAnimation animation = new ViewTranslateAnimation(
							mContext, mBeforeView, mAfterView);
					animation.startTranslateAnimation();
				}
			}
		});
	}

	private void requestGetRandomCity() {
		WebServiceAsyncService wService = new WebServiceAsyncService();
		String cityId = FunctionUtil.getSelectedCityInfo().getCityId();
		cityId = (cityId.equals(CityDataManager.CITY_ID_ALL) || cityId
				.equals(CityDataManager.CITY_ID_INVALID)) ? "" : cityId;
		wService.setParameterToAsyncService(mContext, wService.getNextToken(),
				Operation.OP_SERVICE_ARG_SHAKE_RESUTIL,
				WebServiceRegistrationParameter.PRODUCT_SHAKE_RESUTIL,
				new String[] { cityId },
				WebServiceUrlPortManager.ACTION_URL_PORT_CHAKE_RESUTIL, this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		wService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,
					int index) {
				responseGetRandomStore(result);
				mShakeListener.start();
			}
		});
	}

	private void responseGetRandomStore(Object result) {
		ResponseBean response = WebServiceUtils.getObjectResultToBaseInfo(
				result, StoreAddressInfo.class);
		if (Tools.onPostCheck(mContext, response)) {
			return;
		}

		List<? extends BaseModel> list = response.getReturnList();
		if (list.size() == 0) {
			return;
		}

		List<StoreAddressInfo> storeList = new ArrayList<StoreAddressInfo>();
		for (BaseModel info : list) {
			storeList.add((StoreAddressInfo) info);
		}

		mRandomStore = storeList.get(0);
		Log.d(TAG,
				"responseGetRandomStore: (" + mRandomStore.getStoreId() + ", "
						+ mRandomStore.getStoreName() + ", "
						+ mRandomStore.getStoreAddress() + ", "
						+ mRandomStore.getStoreLatitude() + ", "
						+ mRandomStore.getStoreLongitude() + ")");
		mStoreName.setText(mRandomStore.getStoreName());
		mStoreAddress.setText(mRandomStore.getStoreAddress());
	}

	@Override
	public void cancelUpdate(Object... params) {

	}

	/** listener for click event in random store information. */
	private OnClickListener mGotoSeeStoreDetail = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Log.d(TAG, "onClick view=" + v);
			Intent intent = new Intent(mContext, ContainerActivity.class);
			intent.putExtra(ApplicationManager.KEY_PUT_EXTRA_SELECTED_STORE_ID,
					mRandomStore.getStoreId());
			// jump to store detail page and let the first product as default
			// one.
			intent.putExtra(
					ApplicationManager.KEY_PUT_EXTRA_DEFAULT_PRODUCT_ID, 0);
			Log.d(TAG, "store id ===> " + mRandomStore.getStoreId());
			intent.putExtra(ApplicationManager.INTENT_KEY,
					ApplicationManager.INTENT_FRAGMENT_STORE_DETAIL);
			((FragmentActivity) mContext).startActivityForResult(intent, 0);
			mBeforeView.setVisibility(View.VISIBLE);
			mAfterView.setVisibility(View.GONE);
		}
	};

	public void playSounds(int resId) {
		Log.d(TAG, "playSounds");
		AudioManager am = (AudioManager) mContext
				.getSystemService(Context.AUDIO_SERVICE);
		float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float audioCurrentVolumn = am
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		float volumnRatio = audioCurrentVolumn / audioMaxVolumn;
		mSoundPool.play(resId, volumnRatio, volumnRatio, 1, 0, 1);
	}
}
